<?php

namespace App\Services;

use Illuminate\Support\Facades\Log;
use JPush\Client as JPushClient;

class JPushService
{
    protected $client;

    public function __construct()
    {
        $this->client = new JPushClient('9af16f1b976ef00e7ba79b65', '64dba778f39336801dd186bf');

    }





    public function pushNotify($registration_id, $message, $extraParams)
    {
        if (is_array($registration_id)) {
            foreach ($registration_id as $id) {
                $this->sendPushNotification($id, $message, $extraParams);
            }
        } else {
            $this->sendPushNotification($registration_id, $message, $extraParams);
        }
    }

    private function sendPushNotification($registration_id, $message, $extraParams)
    {
        try {
            $result = $this->client->push()
                ->setPlatform(['android', 'ios'])
                ->addRegistrationId($registration_id)
                ->setNotificationAlert($message['title'], $message['content'])
                ->setMessage($extraParams)
                ->androidNotification($message['title'], [
                    'intent' => [
                        'url' => $extraParams,
                    ],
                ])
                ->send();

            if ($result['http_code'] == 200) {
                Log::info($result);
            } else {
                Log::error('极光推送失败', $result);
            }
        } catch (\Exception $e) {
            Log::error('极光推送异常', (array)$e);
        }
    }



    public function pushNotifyToAll($message,$extraParams)
    {
        try {
            $result = $this->client->push()
                ->setPlatform('all')
                ->addAllAudience()
                ->setNotificationAlert($message['title'], $message['content'])
                ->setMessage($extraParams)
                ->androidNotification($message['title'], [
                    'intent' => [
                        'url' => $extraParams,
                    ],
                ])
                ->send();
            if ($result['http_code'] == 200) {
                Log::info('极光推送成功');
            } else {
                Log::error('极光推送失败', $result);
            }
        } catch (\Exception $e) {
            Log::error('极光推送异常', (array)$e);
        }
    }

}
